package de.grosjohann.android.feuerwehr.service;

import android.app.IntentService;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import de.grosjohann.android.feuerwehr.util.FileUtil;
import de.grosjohann.android.feuerwehr.widget.InfoWidgetProvider;

public class WidgetUpdateService
  extends IntentService {

  private static final String NAME = "WidgetUpdateService";
  private static final int SLEEP_TIME = 2000;
  private static final int MAX_SLEEP_TIME = 10000;

  public WidgetUpdateService() {
    super(NAME);
  }

  @Override
  protected void onHandleIntent(Intent newIntent) {

    Log.d(NAME, "handle");
    try {
      Context ctx = getApplicationContext();

      //Ueberpruefung, ob Dateien zu lesen sind.
      int sleepTimer = 0;
      while (!FileUtil.isFileAvailable(ctx, FMSUpdateService.FMS_STATUS_DATA)
          && !FileUtil.isFileAvailable(ctx, WeatherNotificationService.WEATHER_DATA)) {

        Thread.sleep(SLEEP_TIME);
        sleepTimer += SLEEP_TIME;
        if (sleepTimer >= MAX_SLEEP_TIME) {
          Log.w(NAME, "max. SleepTime reached");
          return;
        }
      }

      sendBroadcast();

    } catch (Exception ex) {
      Log.e(NAME, ex.getMessage(), ex);
    }
  }

  private void sendBroadcast() {
    AppWidgetManager widgetManager = AppWidgetManager.getInstance(this);
    ComponentName widgetComponent = new ComponentName(this, InfoWidgetProvider.class);
    int[] widgetIds = widgetManager.getAppWidgetIds(widgetComponent);

    Intent updateIntent = new Intent();
    updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, widgetIds);
    updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);

    sendBroadcast(updateIntent);
    Log.i(NAME, "send broadcast");
  }
}
